package org.lookahead.parent.database.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lookahead.parent.database.plugins.SqlLogInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
@AllArgsConstructor
@EnableConfigurationProperties(MybatisPlusProperties.class)
@Slf4j
public class MyBatisPlusConfig {

//    private final TenantLineHandler tenantLineHandler;

    @Bean
    @ConditionalOnMissingBean(MybatisPlusInterceptor.class)
    public MybatisPlusInterceptor mybatisPlusInterceptor(MybatisPlusProperties prop) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 配置租户拦截器
//        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(tenantLineHandler));
        // 配置分页拦截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setMaxLimit(prop.getPageLimit());
        paginationInnerInterceptor.setOverflow(prop.getOverflow());
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        log.info("MyBatisPlusConfig:MaxLimit:{},Overflow:{}", prop.getPageLimit(), prop.getOverflow());
        return interceptor;
    }

    /**
     * mybatis-plus自3.4.0起采用新的分页插件,一缓和二缓遵循mybatis的规则,
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

    /**
     * sql 日志
     *
     * @return SqlLogInterceptor
     */
    @Bean
    @ConditionalOnProperty(value = "la.mybatis-plus.sql-log", matchIfMissing = true)
    public SqlLogInterceptor sqlLogInterceptor() {
        return new SqlLogInterceptor();
    }


//
//    @Override
//    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
//        return super.getMethodList(mapperClass);
//    }
//
//    @Bean
//    public MybatisPlusJoinConfig mybatisPlusJoinConfig() {
//        return MybatisPlusJoinConfig.builder()
//                // 查询字段别名关键字
//                .columnAliasKeyword("as")
//                // 表、left join、right join、inner join 表别名关键字
//                .tableAliasKeyword("as")
//                .build();
//    }

}
